#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/1/13 下午11:53
# @Author : Shi Lei
# @File : RWConfig.py
import configparser
import os
import PublicFunction as pf
from Log import logger

cFile = 'Config.ini'

def ReadToolConf():
    """读取视频剪辑配置参数"""
    section = 'tool'
    m4s_folder = get_value(section, "m4s_folder",'')
    ocs = get_value(section, "only_command_statement",'1')
    return m4s_folder, ocs

def get_ConfigParser():
    """生成配置文件对象"""
    # Win10系统文件的编码应该为ANSIC,文件中有汉字，则read(root_path, encoding='utf-8')
    conf = configparser.ConfigParser()
    try:
        cFile_path = os.path.join(pf.get_basic_path()+'/'+pf.get_config_dir(), cFile)  # 正式运行环境
        if not os.path.exists(cFile_path):    # 应用环境
            cFile_path = os.path.join(pf.get_config_dir(),cFile)  # 调试环境
            logger.debug("没有在容器内的映射目录({0})里找到配置文件,可能原因是配置文件没有拷贝到宿主机的挂载目录或者当前应用没有部署在容器内，将在当前文件夹{1}下查找配置文件。".format(pf.get_basic_path(),pf.get_current_directory()))
        if not os.path.exists(cFile_path):
            raise RuntimeError("配置文件丢失({0})！".format(cFile))
        root_path = os.path.abspath(cFile_path)
        conf.read(root_path, encoding='utf-8-sig')  # 文件路径
    except Exception as e:
        logger.error(e)
    return conf

conf = get_ConfigParser()

def get_value(section, option, default=''):
    """根据键找值"""
    value = default
    if conf:
        try:
            value = conf.get(section, option)
        except Exception as e:
            logger.error(e)
    return value


def WriteConf():
    """
    写入配置文件(不可用，未测试)
    """
    file_name = os.path.join(pf.get_basic_path(),'/ceshi/conf/app.conf')
    conf = configparser.ConfigParser()
    root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    conf.read(file_name)  # 文件路径
    conf.set("mysql", "host", "1234")  # 修改指定section 的option
    conf.write(open(root_path + '/ceshi/conf/app.conf', 'w'))


if __name__ == '__main__':
    print(ReadToolConf())

    """
    打印内容：
    ('00:01:00', '99:00:00', 'C:\\Projects\\BatchRename\\91847417', 'C:\\Projects\\BatchRename\\91847417\\dest')
    ('C:\\Program Files\\ffmpeg-full\\bin\\ffmpeg', 'C:\\Projects\\BatchRename\\91847417', 'C:\\Projects\\BatchRename\\91847417\\dest')
    ('幼小衔接 数学视频课48课.txt', 'C:\\Projects\\BatchRename\\91847417')
    """